<template>
    <div class="course-plan">
        <!-- 类型 提示 -->
        <div class="course-type">
            <div class="title">
                <span class="text">课程</span>
                <span class="label">{{state}}</span>
            </div>
            <div class="label-type">
                <span>当日完成</span>
                <span>补课</span>
                <span>未完成</span>
            </div>
        </div>
        <!-- 日历 -->
        <div class="calendar">
            <swiper class="swiper" interval="2000" duration="600" vertical="true" :next-margin="nextMargin" :current="current" @change="swiperchange($event)">
                <!-- <div class="weui-cell-item" > -->
                <swiper-item v-for="(item,index) in calendar" :key="index">
                    <div class="year-month">{{item.year}}.{{item.month}}</div>
                    <div class="week-item clearfloat">
                        <div class="fl" v-for="(week,wIndex) in weekLabel" :key="wIndex">
                            <span>{{week}}</span>
                        </div>
                    </div>
                    <div class="calendar-day clearfloat">
                        <div class="fl" v-for="(day,dIndex) in item.days" :key="dIndex" :class="{stage: day.state_flag == 1}">
                            <form @submit="formSubmit($event,day)" report-submit>
                                <button formType="submit" class="form-btn">
                                    <span :class="{finish: day.finish_state == 1,mend: day.finish_state == 2, unfinished: day.finish_state == 3}">{{day.day > 0 ? day.day : ''}}</span>
                                </button>
                            </form>
                            <!-- <span  @click.stop="gotoRouter(day)" :class="{finish: day.finish_state == 1,mend: day.finish_state == 2, unfinished: day.finish_state == 3}">{{day.day > 0 ? day.day : ''}}</span> -->
                        </div>

                    </div>
                </swiper-item>
                <!-- </div> -->
            </swiper>
            <!-- <img class="calendar-down" v-if="!swiperFlag" src="http://mobuz-mp.gz.bcebos.com/matter/calendar_down.png"> -->
        </div>
        <!-- 计划阶段 -->
        <div class="plan-stage">
            <div class="menu-title">本期计划</div>
            <div class="scroll-controller">
                <scroll-view class="scroll-view_H" scroll-x style="width: auto;overflow:hidden;transform:translateZ(1px)">
                    <div class="scroll-view-item_H" :class="{active: stageIndex === index}" v-for="(item,index) in courseStateList" :key="index" :style="{'background-image' : 'url('+item.stage_cover+')'}" @click="planStage(item,index)">
                        <div class="time">{{item.start_time+'~'+item.end_time}}</div>
                    </div>
                </scroll-view>
            </div>
        </div>
    </div>
</template>

<script>
import { obtainCourseStage, obtainCourseStudentFinish, saveStudentFormId ,statAwardsCase} from "@/config/api";
import { dateRegExp } from "@/config/mUtils";
import { showMessager } from "@/config/wUtils";
export default {
    components: {
    },
    data() {
        return {
            // 课程ID
            batch_id: '',
            // 学员ID
            student_id: '',
            // 日历
            calendar: [],
            // 用户信息
            userInfo: {},
            // 课程阶段列表
            courseStateList: [],
            // 星期标注
            weekLabel: ["日", "一", "二", "三", "四", "五", "六"],
            // 课程开始状态
            courseState: 0,
            // 获取学员的课程完成度
            courseFinish: [],
            // 保存课程完成度的数据
            saveFinishDate: [],
            // 课程开课时间
            courseStartTime: "",
            // 日历轮播 索引值
            current: 0,
            index: 0,
            // 保存阶段期间的日期
            saveStageDate: [],
            // 判断当前阶段是否显示
            stageIndex: null,
            // 判断用户是否拉动过日历
            swiperFlag: false,
            // 下面顶底
            nextMargin: "80rpx",
            // 日历高度设置的定时器
            timer: null,
            // 进入新界面，防止他重复点击
            astrictClickFlag: false,
            // 提示他的课程五天内有权回看
            remindFlag: false,
        };
    },

    computed: {
        state() {
            let str = "";
            if (this.courseState == 0) {
                str = "未开始";
            }
            if (this.courseState == 1) {
                str = "进行中";
            }
            if (this.courseState == 2) {
                str = "结束了";
            }
            return str;
        }
    },
    onShow() { 
        // let pages = getCurrentPages();
        // let Page = pages[pages.length - 1];//当前页
        // let prevPage = pages[pages.length - 2];  //上一个页面
        // console.log('当前页：',Page)
        // console.log('上一页页：',pages)
        let status  = wx.getStorageSync('plan_state')
        if (status == 1) {
            this.init()     
            wx.setStorageSync('plan_state',0)
        } else {
            if (!this.calendar.length) {
                this.init()
                wx.setStorageSync('plan_state',0)
            } 
        }
    },
    async mounted() {
        this.remindFlag = false;
        let status  = wx.getStorageSync('plan_state')
        if (status == 1) {
            this.init()     
            wx.setStorageSync('plan_state',0)
        } else {
            if (!this.calendar.length) {
                this.init()
                wx.setStorageSync('plan_state',0)
            } 
        }
    },
    methods: {
        async init () {
            this.current = 0;
            this.index = 0;
            this.calendar = [];
            this.courseStateList = [];
            this.courseFinish = [];
            this.saveFinishDate =  [];
            this.courseStartTime = [];
            this.saveStageDate = [];
            // 本机用户信息
            this.userInfo = await wx.getStorageSync("userInfo");
            // 学员ID
            this.student_id = await wx.getStorageSync("student_id");
            // 批次ID
            this.batch_id = await wx.getStorageSync("batch_id");
            
            // console.log(this.userInfo,'......微信信息');
            // 获取用户信息
            await this.getCourseStage();
        },
        async formSubmit (e,day) {
            console.log(e.target.formId,day,'formid')
            this.gotoRouter(day)
            // 保存用户点击的formid
            await saveStudentFormId(this.userInfo.openId,e.target.formId).then(res => {})
            
        },
        // 获取课程计划
        async getCourseStage() {
            wx.showLoading({title: '加载中'})
            await obtainCourseStage(this.batch_id)
                .then(async res => {
                    console.log("课程计划", res);
                    if (res.status === 200) {
                        // 课程阶段
                        this.courseStateList = await res.data;
                        // 课程状态
                        this.courseState = await res.courseState;
                        // 课程开课时间
                        this.courseStartTime = (await res.startTime) - 0;
                        // 获取课程完成度
                        await this.getCourseFinish();
                        // 运行日历算法
                        await this.runSystem(res.startTime);
                        if (res.data.length) {
                            console.log('计算')
                            // 当前时间
                            let currentDay = new Date(new Date(new Date().toLocaleDateString()).getTime()).getTime();
                            // 一天的时间戳
                            let day_item = 60 * 60 * 24 * 1000;
                            if (res.data) {
                                let startDay = res.data[0].section[0].section_day
                                let endDay = res.data[res.data.length-1].section[res.data[res.data.length-1].section.length-1].section_day
                                // 获取课程小节的开启的时间戳
                                let startTimestamp = this.courseStartTime + (startDay - 1) * day_item;
                                // 获取课程小节的结束的时间戳
                                let endTimestamp = this.courseStartTime + (endDay-1) * day_item;
                                console.log('当前时间',currentDay)
                                console.log('开始时间',startTimestamp)
                                console.log('结束时间',endTimestamp)
                                if ( (currentDay >= startTimestamp) && (currentDay < endTimestamp)) {
                                    this.courseState = 1
                                } else  if (currentDay < startTimestamp) {
                                    this.courseState = 0
                                } else  if (currentDay > endTimestamp) {
                                    this.courseState = 2
                                }
                                
                            }
                            console.log('状态...',this.courseState)
                        }
                    }
                     wx.hideLoading()
                })
                .catch(err => {
                    console.error(err);
                    wx.hideLoading()
                });
        },
        // 获取学员的课程完成度
        async getCourseFinish() {
            this.saveFinishDate = [];
            await obtainCourseStudentFinish(this.student_id)
                .then(res => {
                    console.log("课程完成度", res);
                    // 一天的时间戳
                    let day_item = 60 * 60 * 24 * 1000;
                    if (res.status === 200) {
                        this.courseFinish = res.data;
                        // 遍历课程阶段
                        for (let i = 0; i < this.courseStateList.length; i++) {
                            if (this.courseStateList[i].section.length) {
                                // 遍历课程阶段的单节
                                for (let j = 0; j < this.courseStateList[i].section.length; j++) {
                                    // 单节
                                    let section = this.courseStateList[i].section[j];
                                    
                                    // 获取今天零点的时间
                                    let currentDay = new Date(new Date(new Date().toLocaleDateString()).getTime());
                                    // 获取课程小节的开启的时间戳
                                    let timestamp = this.courseStartTime + (section.section_day - 1) * day_item;
                                    if ( timestamp <= currentDay) {
                                        // console.log('今天到以往的', section.finish_state)
                                        this.saveFinishDate.push({
                                            year: dateRegExp(timestamp,"yyyy"),
                                            month: dateRegExp( timestamp, "MM"),
                                            day: dateRegExp(timestamp,"dd") - 0,
                                            finish_state: section.finish_state || 3,
                                            section_id: section.section_id
                                        });
                                    }
                                    // 编辑课程完成度的列表
                                    for ( let k = 0; k < this.courseFinish.length; k++) {
                                        // 在课程阶段的列表中，添加完成度的字段
                                        if ( section.section_id === this.courseFinish[k].section_id) {
                                            this.$set(this.courseStateList[i].section[j],"finish_state",this.courseFinish[k].finish_state);
                                            // 获取课程小节的开启的时间戳
                                            let timestamp = this.courseStartTime + (section.section_day - 1) * day_item;
                                            // 保存课程完成度的数据
                                            this.saveFinishDate.push({
                                                year: dateRegExp(timestamp,"yyyy"),
                                                month: dateRegExp( timestamp, "MM"),
                                                day: dateRegExp(timestamp,"dd") - 0,
                                                finish_state: this.courseFinish[k].finish_state,
                                                section_id: this.courseFinish[k].section_id
                                            });
                                        } 
                                    }
                                }
                            }
                        }
                    }
                    console.log(
                        "获取课程小节的开启的时间",
                        this.saveFinishDate
                    );
                })
                .catch(err => {
                    console.error(err);
                });
        },
        // 显示课程计划阶段
        async planStage(stage, index) {
            // saveStageDate
            this.saveStageDate = [];
            let stage_day = [];
            // 一天的时间戳
            let day_item = 60 * 60 * 24 * 1000;
            // 获取阶段的时间天
            for (let i = 0; i < stage.section.length; i++) {
                // 阶段的时间天的时间戳 = 课程开课时间 + 第几天讲课*一天的时间戳
                let timestamp =
                    this.courseStartTime +
                    (stage.section[i].section_day - 0 - 1) * day_item;
                this.saveStageDate.push({
                    year: dateRegExp(timestamp, "yyyy"),
                    month: dateRegExp(timestamp, "MM"),
                    day: dateRegExp(timestamp, "dd") - 0,
                    section_id: stage.section[i].section_id
                });
            }
            // 是否取消阶段显示效果
            let flag = false;
            if (this.stageIndex == index) {
                this.stageIndex = null;
                flag = false;
            } else {
                flag = true;
                this.stageIndex = index;
            }
            // 日历跟阶段比较，根据日期来比较。最终结果给用户展示阶段天数
            for (let i = 0; i < this.calendar.length; i++) {
                console.log(this.calendar[i].month, stage);
                let curMonth = this.calendar[i].month;
                for (let j = 0; j < this.calendar[i].days.length; j++) {
                    // 初始化状态 取消所有阶段显示效果
                    this.$set(this.calendar[i].days[j], "state_flag", 0);
                    if (flag) {
                        for (let k = 0; k < this.saveStageDate.length; k++) {
                            // 根据月份和日期比较
                            if ( this.saveStageDate[k].month == curMonth && this.saveStageDate[k].day == this.calendar[i].days[j].day ) {
                                // 显示阶段天
                                this.$set(this.calendar[i].days[j],"state_flag",1);
                                this.$set(this.calendar[i].days[j],"section_id",this.saveStageDate[k].section_id);
                            }
                        }
                    }
                }
                // 滑动到阶段的当前月份
                if (this.calendar[i].month == stage.start_time.substring(0, 2)) {
                    this.current = i;
                    let num = parseInt(this.nextMargin);
                    console.log("日历的天数", this.calendar[i].days.length);
                    if (this.calendar[i].days.length >= 36) {
                        num = 160
                        this.nextMargin = num + "rpx";
                    } else {
                        num = 225
                        this.nextMargin = num + "rpx";
                    }
                }
            }
            
            console.log('阶段',stage)
        },
        // 日历滑动监听
        swiperchange(event) {
            console.log(event);
            clearInterval(this.timer);
            if (event.target.source === "touch") {
                if (this.current == 0 && this.index > 1) {
                    //卡死时，重置current为正确索引
                    this.current = this.index;
                } else {
                    this.timer = null;
                    let index = event.target.current;
                    let num = parseInt(this.nextMargin);
                    console.log("日历的天数", this.calendar[index].days.length);
                    if (this.calendar[index].days.length >= 36) {
                        num = 160
                        this.nextMargin = num + "rpx";
                    } else {
                        num = 225
                        this.nextMargin = num + "rpx";
                    }
                    this.index = event.target.current;
                    this.swiperFlag = true;
                    console.log("当前索引", this.current);
                }

                this.current = event.target.current;
            }
        },
        // 运行时间 num为几个月，即显示几个月开始讲课
        async runSystem(timestamp, num) {
            // 月份计算
            // 加速几个月 ，调试用。 默认月份+1
            let seep = 1 + (num || 0);
            for (let i = 0; i < 3; i++) {
                // 当前时间
                let now = new Date(timestamp - 0);
                // 月
                let curMonth = 0;
                // 超过12月份后 年份+1
                if (now.getMonth() + seep + i > 12) {
                    now.setFullYear(now.getFullYear() + 1);
                    curMonth = (now.getMonth() + seep + i) % 12;
                } else {
                    curMonth = now.getMonth() + seep + i;
                }
                // 保持数字两位数 例如：01 13
                curMonth =
                    curMonth > 0 && curMonth < 10 ? "0" + curMonth : curMonth;
                // 加入数据
                let days = await this.getSystemDate(
                    now,
                    now.getFullYear(),
                    curMonth
                );
                this.calendar.push({
                    year: now.getFullYear(),
                    month: curMonth,
                    days: days
                });
            }
            console.log(this.calendar);
            if (this.calendar[0].days.length >= 36) {
                this.nextMargin = "160rpx";
            } else {
                console.log(222222222);
                this.nextMargin = "225rpx";
            }
        },
        // 获取月日历
        async getSystemDate(now, year, month) {
            console.log(now.getMonth(year, month), month);
            let curDate = new Date(year, month, 1);
            // 获取当前年份
            /* 获取当前月份 */
            let curMonth = month;
            /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
            // curDate.setMonth(curMonth + 1);
            /* 将日期设置为0  */
            curDate.setDate(0);

            /* 返回当月的天数 */
            let days = new Date(year, month, 0).getDate();
            // 闰年的2月份加一天
            if (month == 2) {
                days = days + (year % 400 == 0 ? 1 : year % 100 != 0 && year % 4 == 0 ? 1 : 0);
            }
            console.log(days);
            // 每个月的第一天
            console.log(year, curMonth);
            let firstDay = new Date(year, month - 1, 1);
            //第一天星期几(0-6)
            let weekday = firstDay.getDay();
            console.log("第一天星期几", weekday);
            // 补齐前面的空格
            let fillArry = [];
            for (let i = 0; i < weekday; i++) {
                // dayStr += '+ ';
                fillArry.push({
                    day: 0,
                    // 0无状态 1 已完成 2补课 3未完成
                    finish_state: 0
                });
            }
            let dayArry = [];
            for (let i = 1; i <= days; i++) {
                // 课程计划的状态
                let finish_state = 0;
                let section_id = '';
                for (let j = 0; j < this.saveFinishDate.length; j++) {
                    let item = this.saveFinishDate[j];
                    if (item.month - 0 == curMonth && item.day == i) {
                        finish_state = item.finish_state;
                        section_id = item.section_id
                    }
                }
                dayArry.push({
                    day: i,
                    month,
                    year,
                    // 课程计划的状态 0无状态 1 已完成 2补课 3未完成
                    finish_state,
                    // 课程ID
                    section_id
                });
            }
            // 跟填充的日期合并一起，方便循环日历
            dayArry = [...fillArry, ...dayArry];
            return dayArry;
        },
        // 跳转界面
        async gotoRouter (item) {
            // 今天零点时间
            let currentDay = new Date(new Date(new Date().toLocaleDateString()).getTime()).getTime();
            // 点击的日历时间
            let itemDate = new Date(item.year, item.month-1, item.day).getTime();
            if (item.section_id && (item.state_flag || item.finish_state)) {
                if (currentDay < itemDate) {
                    showMessager("请按照阶段学习");
                    return false;
                }
                // 预防重复点击
                if (!this.astrictClickFlag) {
                    this.astrictClickFlag = true;
                    setTimeout(async () => {
                        if (this.courseStartTime >= 1542643200000) {
                            await statAwardsCase(this.student_id,this.batch_id)
                                .then(res => {
                                    this.astrictClickFlag = false;
                                    if (res.status === 200) {
                                        wx.navigateTo({
                                            url: '../courseParticulars/main?section_id='+item.section_id+'&batch_id='+this.batch_id
                                        })
                                    } else if (res.status === 202) {
                                        // 提醒只有一次
                                        if (!this.remindFlag) {
                                            wx.showModal({
                                                content: '课程结束后，5天内拥有课程回看权限',
                                                showCancel: false,
                                                success: ()=> {
                                                    wx.navigateTo({
                                                        url: '../courseParticulars/main?section_id='+item.section_id+'&batch_id='+this.batch_id
                                                    })
                                                }
                                            })
                                            this.remindFlag = true;
                                        } else {
                                            wx.navigateTo({
                                                url: '../courseParticulars/main?section_id='+item.section_id+'&batch_id='+this.batch_id
                                            })
                                        }
                                        
                                    } else {
                                        showMessager(res.msg);
                                    }
                                    
                                })
                                .actch( err => {
                                    showMessager("网络拥堵，请稍后再试");
                                })
                        } else {
                            this.astrictClickFlag = false;
                            wx.navigateTo({
                                url: '../courseParticulars/main?section_id='+item.section_id+'&batch_id='+this.batch_id
                            })
                        }
                       
                    }, 100);
                }
            }
           
        }
    },
     // 下拉刷新
    onPullDownRefresh() {
        // this.index = 0;
        // this.calendar = [];
        // this.courseStateList = [];
        // this.courseFinish = [];
        // this.saveFinishDate =  [];
        // this.courseStartTime = [];
        // this.saveStageDate = [];
        // this.getCourseStage();
        wx.stopPullDownRefresh()
    }
};
</script>

<style  lang="less" scoped>
.clearfloat {
    zoom: 1;
}
.clearfloat:after {
    display: block;
    height: 0;
    content: "";
    clear: both;
    visibility: hidden;
}
.fl {
    float: left;
}
.fr {
    float: right;
}
.course-plan {
    .calendar {
        margin: 27rpx auto 0;
        width: 686rpx;
        height: 775rpx;
        padding-top: 30rpx;
        padding-bottom: 40rpx;
        background: #ffffff;
        box-shadow: 0 0 12rpx 2rpx rgba(223, 223, 223, 0.3);
        border-radius: 14rpx;
        position: relative;
        .calendar-down {
            display: block;
            width: 75rpx;
            height: 25rpx;
            position: absolute;
            bottom: 22rpx;
            left: 50%;
            margin-left: -37.5rpx;
        }
        .swiper {
            width: 100%;
            height: 100%;
            transform: translateZ(1rpx);
            // .weui-cell-item {
            text-align: center;
            .year-month {
                padding: 0rpx 0 20rpx;
                font-family: PingFangSC-Regular;
                font-size: 36rpx;
                color: #666666;
                text-align: center;
            }
            .week-item,
            .calendar-day {
                padding: 0 33rpx;
                font-family: PingFangSC-Light;
                font-size: 0;
                color: #666666;
                text-align: center;
                > div {
                    width: 68rpx;
                    height: 68rpx;
                    margin-right: 24rpx;
                    text-align: center;
                    display: flex;
                    align-items: center;
                    &:nth-child(7n) {
                        margin-right: 0;
                    }
                    span {
                        // align-items: center;
                        // vertical-align:middle;
                        display: block;
                        margin: 0 auto;
                        width: 56rpx;
                        height: 56rpx;
                        line-height: 56rpx;
                        font-size: 28rpx;
                        border-radius: 50%;
                    }
                }
            }
            .week-item {
                > div {
                    span {
                        width: 68rpx;
                    }
                }
            }
            .calendar-day {
                > div {
                    margin-top: 12rpx;
                    &.stage {
                        border-radius: 50%;
                        border: 1rpx solid #bdbdbd;
                        box-sizing: border-box;
                    }
                    form {
                        margin: 0 auto;
                        .form-btn {
                            border:none;
                            text-align:left;
                            padding:0;
                            margin:0;
                            background-color: transparent;
                            &::after {
                                border: none;
                            }
                            > span {
                                text-align: center;
                                &.finish {
                                    color: #ffffff;
                                    background-color: #c1e993;
                                }
                                &.mend {
                                    color: #ffffff;
                                    background-color: #fbf19e;
                                }
                                &.unfinished {
                                    color: #ffffff;
                                    background-color: #e0e0e0;
                                }
                            }
                        }
                    }
                    
                    
                }
            }
            // }
        }
    }
    .course-type {
        padding: 0 32rpx;
        .title {
            margin: 30rpx 0 2rpx;
            > span {
                font-size: 0;
                display: inline-block;
                vertical-align: middle;
                &.text {
                    font-family: PingFangSC-Regular;
                    font-size: 26rpx;
                    color: #666666;
                    margin-right: 14rpx;
                }
                &.label {
                    width: 80rpx;
                    height: 30rpx;
                    line-height: 30rpx;
                    background: #f2f2f2;
                    border-radius: 5rpx;
                    font-family: PingFangSC-Regular;
                    font-size: 20rpx;
                    color: #ee3a29;
                    letter-spacing: 0.55rpx;
                    text-align: center;
                }
            }
        }
        .label-type {
            text-align: right;
            > span {
                margin-left: 51rpx;
                font-family: PingFangSC-Light;
                font-size: 20rpx;
                color: #666666;
                height: 28rpx;
                line-height: 28rpx;
                position: relative;
                &::after {
                    content: "";
                    position: absolute;
                    top: 50%;
                    margin-top: -7rpx;
                    left: -21rpx;
                    width: 14rpx;
                    height: 14rpx;
                    border-radius: 50%;
                }
                &:nth-child(1)::after {
                    background-color: #c1e993;
                }
                &:nth-child(2)::after {
                    background-color: #fbf19e;
                }
                &:nth-child(3)::after {
                    background-color: #e0e0e0;
                }
            }
        }
    }
    .plan-stage {
        margin-top: 38rpx;
        padding: 0 0 25rpx 32rpx;
        .scroll-controller {
            height: 310rpx;
            overflow: hidden;
            white-space: nowrap;
        }
        .menu-title {
            margin-bottom: 23rpx;
            padding-left: 14rpx;
            font-family: PingFangSC-Regular;
            font-size: 28rpx;
            color: #666666;
            height: 40rpx;
            line-height: 40rpx;
            position: relative;
            &::after {
                content: "";
                position: absolute;
                top: 50%;
                margin-top: -14rpx;
                left: 0rpx;
                width: 4rpx;
                height: 28rpx;
                background-color: #ee3a29;
            }
        }
        .scroll-view_H {
            font-size: 0;
            .scroll-view-item_H {
                display: inline-block;
                width: 250rpx;
                height: 300rpx;
                position: relative;
                border-radius: 10rpx;
                background-repeat: no-repeat;
                background-position: center center;
                background-size: cover;
                overflow: hidden;
                // box-sizing: border-box;
                border: 2rpx solid transparent;
                &.active {
                  border: 2rpx solid #ee3a29;
                    // box-shadow: 0 0 0rpx rpx #ee3a29;
                }
                & + .scroll-view-item_H {
                    margin-left: 20rpx;
                }
                .time {
                    position: absolute;
                    bottom: 0;
                    width: 100%;
                    height: 45rpx;
                    line-height: 45rpx;
                    font-family: PingFangSC-Light;
                    font-size: 24rpx;
                    color: #ffffff;
                    text-align: center;
                    background: rgba(51,51,51,0.5);
                }
            }
        }
    }
}
</style>
